
package coffee;

import coffee.listeners.NewMessageEvent;
import coffee.listeners.NewMessageListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 *
 * @author bwolff
 */

public class ReadInStream extends Thread {
        List<NewMessageListener> listenersToRemove = new ArrayList<>();
        List<NewMessageListener> listeners;
        Socket socket;
        Queue<String> queue = new LinkedList<String>();


        public ReadInStream(Socket socket) {
                this.socket = socket;
                listeners = new ArrayList<>();
        }
        
        public void removeNewMessageListener(NewMessageListener l) {
            listenersToRemove.add(l);
        }
        
        public void addNewMessageListener(NewMessageListener l) {
            listeners.add(l);
        }
        
        private void fireNewMessageEvent(NewMessageEvent event) {
            for(NewMessageListener l : listeners) {
                l.processNewMessage(event);
            }
            for(NewMessageListener l : listenersToRemove) {
                listeners.remove(l);
            }
            listenersToRemove.clear();
        }

        @Override
        public void run() {
                try {
                        System.out.println("Thread ReadInStream started.");
                        BufferedReader inStream = new BufferedReader(
                                        new InputStreamReader(socket.getInputStream()));
                        while (true) {
                                String inputLine = inStream.readLine();
                                if (inputLine != null && inputLine.trim() != ""
                                                && inputLine.length() > 0) {
                                        //System.out.println("Recieved: " + inputLine);
                                        queue.offer(inputLine);
                                        fireNewMessageEvent(new NewMessageEvent(new ServerMessage(inputLine)));
                                }
                        }
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}
